// src/utils/firebase.js
import { initializeApp } from "firebase/app";
import { getAnalytics, logEvent, setUserId } from "firebase/analytics";

const firebaseConfig = {
  apiKey: "AIzaSyA1vA9g2nG38tsoN_B8UTHkW_OXe6GN2Gg",
  authDomain: "sliterg-snake-clash.firebaseapp.com",
  projectId: "sliterg-snake-clash",
  //storageBucket: "sliterg-snake-clash.appspot.com", // 修正后缀
  storageBucket: "sliterg-snake-clash.firebasestorage.app",
  messagingSenderId: "495471561680",
  appId: "1:495471561680:web:79290f82c2ac39141147d5",
  measurementId: "G-058HT3VK0G", // 使用 Firebase 配置中的 ID
};

const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
setUserId(analytics, JSON.parse(localStorage.getItem("auth-store"))?.user);

// 公共参数对象（可全局使用）
const commonParams = {
  userId: '',
  platform: 'web'
}
// 更新公共参数的方法
export const updateCommonParams = (newParams) => {
  Object.assign(commonParams, newParams)
}

// 获取当前公共参数的副本（避免直接修改）
export const getCommonParams = () => ({ ...commonParams })

/*
  发送埋点事件（自动合并公共参数）
  @param {string} eventName -- 事件名称
  @param {object} privateParams -- 事件私有参数（优先级高于公共参数）
*/
export const trackEvent = (eventName, privateParams = {}) => {
  // 合并参数：私有参数覆盖公共参数
  const eventParams = {
    ...commonParams,
    ...privateParams,
    // 添加时间戳确保事件唯一性
    timestamp: Date.now()
  }
  logEvent(analytics, eventName, eventParams);
};

// 页面曝光
/**
 * 跟踪页面浏览事件
 * @param {string} screenName 页面名称
 * @param {object} additionalParams 页面额外参数
 */
export const trackScreenView = (screenName, additionalParams = {}) => {
  trackEvent("screen_view", {
    screen_name: screenName,
    ...additionalParams
  });
};

//初始化用户ID
// 在用户登录后调用 updateCommonParams({user_id: '123'})

export { analytics };
